const { VITE_APP_BASE_URL } = import.meta.env;

/**
 * 获取当前页面路由
 */
export const currRoute = () => {
    const pages = getCurrentPages();
    const route = pages[pages.length - 1];
    return route ? route.route : "";
};

/**
 * 获取url参数
 * @param url
 * @param param
 * @returns
 */
export const getQueryParam = (url, param) => {
    const urlObj = new URL(url);
    const searchParams = new URLSearchParams(urlObj.search);
    return searchParams.get(param);
};

/**
 * 向网址中增加参数
 * @param url
 * @param obj 对象
 */
export const addQueryParams = (url, obj) => {
    let symbol = url.indexOf("?") > -1 ? "&" : "?";
    Object.keys(obj).forEach((key, index) => {
        if (index > 0) symbol = "&";
        url += `${symbol}${key}=${obj[key]}`;
    });
    return url;
};

/**
 * @description 是否为空
 * @param {unknown} value
 * @return {Boolean}
 */
export const isEmpty = (value: unknown) => {
    return value == null && typeof value == "undefined";
};

/**
 * 判断是否是url
 * @param str
 * @returns
 */
export function isUrl(str: string): boolean {
    return str.indexOf("http:") != -1 || str.indexOf("https:") != -1;
}

/**
 * 获取路径
 * @param path
 * @returns
 */
export function getUrl(path: string): string {
    if(isUrl(path)) {
        return path;
    } else {
        return VITE_APP_BASE_URL ? `${VITE_APP_BASE_URL}/${path}`: (window.location.protocol + '//' + window.location.host + `/${path}`);
    }
}

/**
 * 手机号去除敏感词
 */
export function mobileConceal(mobile: string): string {
    return mobile.substring(0, 3) + "****" + mobile.substr(mobile.length - 4);
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    const delay = t || 500;
    let timer;
    return function () {
        const args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            typeof fn === "function" && fn();
        }, delay);
    };
};

/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
    let last;
    let timer;
    const interval = t || 500;
    return function () {
        const now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                typeof fn === "function" && fn();
            }, interval);
        } else {
            last = now;
            typeof fn === "function" && fn();
        }
    };
};

/**
 * 获取经纬度
 */
export const getLocation = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: "wgs84",
            success: function (res) {
                resolve(res);
            },
        });
    });
};
